﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Rigidbody))]
public class Tank : MonoBehaviour
{

    Data.Account account;
    public Data.Account Account
    {
        get
        {
            return account;
        }
    }

    TankPanel uiPanel;
    Rigidbody rigibody;
    GameObject bulletPrefab;

    public Transform firePoint;
    public float moveSpeed = 10;
    public float rotateSpeed = 5;

    void Awake()
    {
        rigibody = this.GetComponent<Rigidbody>();
        bulletPrefab = Resources.Load<GameObject>("Bullet");
    }

    public void Move(float vertical, float horizon)
    {
        rigibody.velocity = transform.forward * vertical * moveSpeed;
        transform.eulerAngles += Vector3.up * horizon * rotateSpeed;
    }

    public void Move(Data.ReqPosition req)
    {
        transform.position = Util.PV2UV(req.position);
        transform.forward = Util.PV2UV(req.forward);
    }

    public void Init(Data.Account acc)
    {
        this.account = acc;

        Vector3 position = SpawnPoints.Instance.GetPoint(acc.point);
        this.transform.position = position;
        foreach (var item in this.GetComponentsInChildren<MeshRenderer>())
        {
            item.material.color = Util.PC2UC(acc.color);
        }

        GameObject prefab = Resources.Load<GameObject>("TankPanel");
        var ui = GameObject.Instantiate(prefab);
        ui.transform.SetParent(UIManager.Instance.CanvasRect);
        uiPanel = ui.GetComponent<TankPanel>();
        uiPanel.Init(this, acc);
    }

    //本机玩家调用
    public void Fire()
    {
        var go = GameObject.Instantiate(bulletPrefab);
        go.transform.position = firePoint.position;
        go.transform.rotation = firePoint.rotation;
        go.GetComponent<Bullet>().Fire(this);
        Destroy(go,3f);
    }

    //远程调用
    public void Fire(Data.ReqPosition req)
    {
        Move(req);
        Fire();
    }

    //被打中
    public void OnDamage(Tank target)
    {
        Data.ReqHit hit = new Data.ReqHit();
        hit.hitname = target.account.username;
        hit.hurtname = this.account.username;

        NetworkManager.Instance.Send(Protocal.PlayerDamage_CMD, hit);
    }


    //获取伤害
    public void TakeHurt(int hurtedHp)
    {
        account.hp = hurtedHp;
        uiPanel.SetHp((float)account.hp / account.defaultHp);


        //玩家死亡
        if (account.hp == 0)
        {
            OnDead(true);
        }
    }

    //获取奖励
    public void TakeReward()
    {

    }

    public void OnDead(bool hitdead = false)
    {
        if (hitdead)
        {
            var prefab = Resources.Load<GameObject>("BustedTank");
            var burst = Instantiate(prefab, transform.position, transform.rotation);
            Destroy(burst, 3f);
        }

        Destroy(uiPanel.gameObject);
        Destroy(gameObject);
    }
}
